package org.example.musicserver.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.musicserver.common.Result;
import org.example.musicserver.entity.Banner;
import org.example.musicserver.mapper.BannerMapper;
import org.example.musicserver.service.BannerService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
@Slf4j
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner> implements BannerService {
    @Resource
    private BannerMapper bannerMapper;

    @Override
    public List<Banner> getAllBanner() {
        QueryWrapper<Banner> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        return bannerMapper.selectList(queryWrapper);
    }

    @Override
    public Result addBanner(MultipartFile file) {
        String[] split = file.getOriginalFilename().split("\\.");
        String s = split[split.length - 1];
        String path = "img/swiper/" + System.currentTimeMillis() + "." +  s;
        File newFile = new File(path);
        try {
            if(!newFile.exists()){
                newFile.createNewFile();
            }

            file.transferTo(newFile.toPath());
        } catch (IOException e) {
            log.warn("操作失败{}",e);
            return Result.error("添加失败");
        }

        Banner banner = new Banner();
        banner.setBannerUrl("/" + path);
        if(bannerMapper.insert(banner) > 0){
            return Result.success("添加成功");
        }
        return Result.error("添加失败");
    }

    @Override
    public Result updateBanner(Integer id, MultipartFile file) {
        String[] split = file.getOriginalFilename().split("\\.");
        String s = split[split.length - 1];
        String path = "img/swiper/" + System.currentTimeMillis() + "." +  s;
        File newFile = new File(path);
        try {
            if(!newFile.exists()){
                newFile.createNewFile();
            }

            file.transferTo(newFile.toPath());
        } catch (IOException e) {
            log.warn("修改失败{}",e);
            return Result.error("修改失败");
        }

        Banner banner = new Banner();
        banner.setId(id);
        banner.setBannerUrl("/" + path);
        if(bannerMapper.updateById(banner) > 0){
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }

    @Override
    public Result deleteBanner(Integer id) {
        if(bannerMapper.deleteById(id) > 0){
            return Result.success("删除成功");
        }
        return Result.error("删除成功");
    }
}
